package com.zhongzhi.thread;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;

import com.zhongzhi.bean.Configuration;
import com.zhongzhi.common.Common;
import com.zhongzhi.util.ClientUtil;
import com.zhongzhi.util.JsonResult;
import com.zhongzhi.util.PageUtil;

import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import lombok.extern.log4j.Log4j;
@Log4j
public class ServerTherad extends Thread{
	
	
	@Override
	public void run() {
		while (true) {
			try {
				log.info("主画面:测试连接远端服务器");
				Configuration configuration = Common.getConfiguration();
				configuration.setBoolean1(false);
				String string  = "http://"+configuration.getServerId()+":"+configuration.getServerProt()+"/doosanRadar/ds/teston";
				if (string==null || string.equals("")) {
					pageShow();
					log.info("主画面:测试连接远端服务器失败");
				}
				
				String gethttp = ClientUtil.Gethttp(string);
				JsonResult jsonobj = ClientUtil.Jsonobj(gethttp, JsonResult.class);
				if (jsonobj.getCode()==200) {
					log.info("主画面:测试连接远端服务器成功");
					configuration.setBoolean1(true);
				}else {
					pageShow();
					log.info("主画面:测试连接远端服务器失败");
				}
				
			} catch (Exception e) {
				pageShow();
				log.error("主画面:测试连接远端服务器失败:"+e);
			}
			
			try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void pageShow() {
		Platform.runLater(new Runnable() {
			
			@Override
			public void run() {
				if(Common.isHavaPage()==false) {
					PageUtil util = new PageUtil();
					Stage setPage2 = util.setPage2("/fxml/function/ConnectionFail.fxml", "连接远程服务器失败");
					//关闭时设置画面打开状态为false
					setPage2.setOnCloseRequest(new EventHandler<WindowEvent>() {
						@Override
						public void handle(WindowEvent event) {
							Common.setHavaPage(false);
						}
					});
					//打开时设置画面打开状态为true
					Common.setHavaPage(true);
				}
			}
		});
		
		
	}
}
